var gulp = require('gulp');
var concat = require('gulp-concat');
var uglify = require('gulp-uglify');
var jshint = require('gulp-jshint');
var imagemin = require('gulp-imagemin');
var connect = require('connect');
var serve = require('serve-static');
var browsersync = require('browser-sync');
var postcss = require('gulp-postcss');
var cssnext = require('postcss-cssnext');
var cssnano = require('cssnano');
var browserify = require('browserify');
var source = require('vinyl-source-stream');
var buffer = require('vinyl-buffer');
var babelify = require('babelify');
var plumber = require('gulp-plumber');
var beeper = require('beeper');
var del = require('del');
var config = require('./config.json');
var sourcemaps = require('gulp-sourcemaps');

// 错误处理函数
function onError(err) {
    beeper();
    console.log('Name:', err.name);
    console.log('Reason:', err.reason);
    console.log('File', err.file);
    console.log('Line', err.line);
    console.log('column:', err.column);
}

gulp.task('styles', function () {
    return gulp.src(config.css.src)
        .pipe(concat('all.css'))
        .pipe(plumber({
            errorHandler: onError
        }))
        .pipe(postcss([
            cssnext(),
            cssnano()
        ]))
        .pipe(gulp.dest(config.css.dest));
});

// 脚本任务
gulp.task('scripts', function () {
    return gulp.src('app/js/*.js')
        .pipe(sourcemaps.init())
        .pipe(jshint())
        .pipe(jshint.reporter('default'))
        .pipe(concat('all.js'))
        .pipe(uglify())
        .pipe(sourcemaps.write('dist/maps'))
        .pipe(gulp.dest('dist'));
});

//图片
gulp.task('images', function () {
    return gulp.src('app/img/*')
        .pipe(imagemin())
        .pipe(gulp.dest('dist/img'));
});

//服务器任务
gulp.task('server', function () {
    return connect().use(serve(__dirname))
        .listen(8080)
        .on('listenling', function () {
            console.log("服务器运行在http://loclhost:8080上")
        });
});

//BrowserSync 任务
gulp.task('browsersync', function () {
    return browsersync({
        server: {
            baseDir: './'
        }
    })
});

//Browserify任务
gulp.task('browserify', function () {
    return browserify('./app/js/app.js')
        .transform('babelify', {
            presets: ['env']
        })
        .bundle()
        .pipe(source('bundle.js'))
        .pipe(buffer())
        .pipe(gulp.dest('dist'));
});

// 清除任务
gulp.task('clean', function () {
    return del(['dist']);
});

//监听更改
gulp.task('watch', function () {
    gulp.watch('app/css/*.css', ['styles', browsersync.reload]);
    gulp.watch('app/js/*.js', ['scripts', browsersync.reload]);
    gulp.watch('app/img/*', ['images', browsersync.reload]);
});

// 默认任务
// gulp.task('default', ['styles', 'scripts', 'images', 'server', 'watch']);
gulp.task('default', ['styles', 'scripts', 'images', 'browsersync', 'watch']);



